package org.testfire.realm.util;

import javax.faces.model.SelectItem;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Granum
 * Date: Jan 14, 2007
 * Time: 12:56:11 PM
 */
public class UiTools {

	public static List<SelectItem> toSelectItemList(Collection itemObjects, String valueProperty){
		return toSelectItemList(itemObjects, null, valueProperty, true);
	}

	public static List<SelectItem> toSelectItemList(Collection itemObjects, String valueProperty, boolean idByIndex){
		return toSelectItemList(itemObjects, null, valueProperty, idByIndex);
	}

	public static List<SelectItem> toSelectItemList(Collection itemObjects, String idProperty, String valueProperty){
		return toSelectItemList(itemObjects, idProperty, valueProperty, false);
	}


	private static List<SelectItem> toSelectItemList(Collection itemObjects,
	                                                String idProperty,
	                                                String valueProperty, boolean idByIndex) {
		ArrayList<SelectItem> items = new ArrayList<SelectItem>();
		if (itemObjects.isEmpty()) {
			return items;
		}
		ArrayList itemObjs = new ArrayList(itemObjects);
		Object obj = itemObjs.get(0);
		try {
			Method meth = obj.getClass().getMethod(ReflectionTools.toGetter(valueProperty));
			Method idMeth = null;
			if(idProperty != null){
				idMeth = obj.getClass().getMethod(ReflectionTools.toGetter(idProperty));
			}
			for (int i = 0; i < itemObjs.size(); i++) {
				Object o = itemObjs.get(i);
				String value = String.valueOf(meth.invoke(o));
				if (idByIndex) {
					items.add(new SelectItem(i, value));
				}
				else if(idProperty != null) {
					Object id = idMeth.invoke(o);
					items.add(new SelectItem(id, value));
				}
				else{
					items.add(new SelectItem(o, value));
				}
			}
		} catch (NoSuchMethodException e) {
			throw new NullPointerException("No such method on class: " + obj.getClass() + ": '" + valueProperty + "'.");
		} catch (IllegalAccessException e) {
			throw new NullPointerException(e.getLocalizedMessage());
		} catch (InvocationTargetException e) {
			throw new NullPointerException(e.getLocalizedMessage());
		}
		return items;
	}


}
